package com.quanxi.qxaimain.common.globalException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Author lyx
 * @create 2022/9/1 16:45
 * controller返回结果进行全局封装（其中注释了@NotControllerResponseAdvice的方法都不进行包装）
 */

@RestControllerAdvice(basePackages = {"com.quanxi.qxaimain.controller"})
public class ControllerResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
         // response是ResultVo类型，或者注释了@NotControllerResponseAdvice的方法都不进行封装
        return    !(returnType.getParameterType().isAssignableFrom(ResponseVo.class)
                  ||returnType.hasMethodAnnotation(NotControllerResponseAdvice.class));
    }



    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // String类型不能直接包装
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
                // 将数据包装在ControllerResponseVo里后转换为json串进行返回
            try {
                return objectMapper.writeValueAsString(new ResponseVo(body));
            }catch (JsonProcessingException e){
                throw new GlobalException(e.getMessage());
            }

        }
        return new ResponseVo(body);
    }
}